/*
 * utiles.c
 *
 */

#include "utiles.h"

int openFile(FILE** file,char* location,FILE* defaultFile,char * openMode);

int readEncode(FILE *file,char **buffer){
	int size=0;
	char aux,*tmp;
	aux=fgetc(file);

	while ( (!feof(file) )&& size < 3 ){

			size++;
			tmp = realloc(*buffer,sizeof(char) * (size + 1) );
			if (tmp != NULL) {
				*buffer = tmp;
				(*buffer)[size-1] = aux;
				(*buffer)[size] = '\0';
			}else{
				free(*buffer);
				printf("Fallo la obtencion de memoria\n");
				exit(-1);
			}

			if(size < 3)
				aux=fgetc(file);

	}

	if (size == 0) {
		return EOF;
	}

	return size;
}

int readDecode(FILE *file,char **buffer){
	int size=0;
	char aux,*tmp;
	aux=fgetc(file);
	
	while ( (!feof(file) )&& size < 4 ){
		if(!((aux == ' '))){

			size++;
			tmp = realloc(*buffer,sizeof(char) * (size + 1) );
			if (tmp != NULL) {
				*buffer = tmp;
				(*buffer)[size-1] = aux;
				(*buffer)[size] = '\0';
			}else{
				free(*buffer);
				printf("Fallo la obtencion de memoria\n");
				exit(-1);
			}

			if(size < 4)
				aux=fgetc(file);
		}else{
			aux=fgetc(file);
		}
	}

	if (size == 0) {
		return EOF;
	}

	return size;
}

int abrirArchivos(int argc,char **argv,FILE **f1,FILE **f2,char* file1,char* file2){

	if (openFile(f1,file1,stdin,"rb"))
		return -1;

	if (openFile(f2,file2,stdout,"wb"))
		return -1;

	return 0;
}

int openFile(FILE** file,char* location,FILE* defaultFile,char * openMode){
	if(location == NULL){
		*file = defaultFile;
	}else{
		*file=fopen(location,openMode);

		location = NULL;

		if (*file == NULL) {
			printf(ERROR_ARCHIVOS);
			return -1;
		}
	}

	return 0;
}

